package db;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * This class is used to connect to the database.
 * 
 * @author Brad Hanlon
 *
 */
public class DatabaseConnector {
	
	private Connection conn;
	
	/**
	 * Returns a connection to the database.
	 * 
	 * @return A database connection.
	 */
	public Connection getConnection(){
		return conn;
	}
	
	/**
	 * Attempts to connect to the database.  Returns a boolean value
	 * dependent on the outcome.
	 * 
	 * @return Boolean value - true if successful in connection
	 * 						 - false if unsuccessful
	 */
	public boolean connect(){
		Properties p = new Properties();
		try {
			
			FileInputStream fis = new FileInputStream("db.properties");
			p.load(fis);

			String url = p.getProperty("url");
			
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
			conn = DriverManager.getConnection(url);
			return true;
		} catch (ClassNotFoundException e) {
			System.err.println("Could not find the database driver");
		} catch (SQLException e) {
			if(e.toString().contains("not found")){
				try {
					String url = p.getProperty("url");
					conn = DriverManager.getConnection(url + ";create=true");				
					
					return true;
				} catch (SQLException e1) {
					System.out.println("Another error occured");
					e1.printStackTrace();
				}
			}
		} catch (FileNotFoundException e) {
			System.out.println("** db.properties not found **");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IO exception");
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * Disconnects from the database.
	 */
	public void disconnect(){
		try {
			conn.close();
		} catch (SQLException e) {
			System.err.println("Error on database close:");
			e.printStackTrace();
		}
	}
	
}
